#include <sys/types.h>
#include <sys/socket.h>
#include <stddef.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <sys/un.h>
#include <stdio.h>

#define SPATH "server.socket"

int main(int argc, char* argv[])
{
	int sockfd;
	struct sockaddr_un addr, cliaddr;
	char buf[BUFSIZ];

	sockfd = socket(AF_UNIX, SOCK_STREAM, 0);

	addr.sun_family = AF_UNIX;
	strcpy(addr.sun_path, SPATH);

	socklen_t len = offsetof(struct sockaddr_un, sun_path)+strlen(addr.sun_path);
	
	unlink(SPATH);

	bind(sockfd, (struct sockaddr*)&addr, len);

	srand((unsigned int)time(NULL));

	listen(sockfd, 5);	

	while(1)
	{
		len = sizeof(cliaddr);/////////this is necessary, and here could not use "offsetof"  
	
		int cfd = accept(sockfd, (struct sockaddr*)&cliaddr, &len);
	
		len -= offsetof(struct sockaddr_un, sun_path);
		cliaddr.sun_path[len] = '\0';		
	
		printf("new client connect: %s\n", cliaddr.sun_path);
		
		while(1)
		{
			int ret = read(cfd, buf, sizeof(buf));
			printf("ret: %d\n",ret);
			write(STDOUT_FILENO, buf, ret);
			if(write(cfd, buf, ret)<0)perror("write:");
		}
		close(cfd);
	}

	close(sockfd);
	return 0;
}
